<template>
  <common-dialog
    :dialog-visible.sync="visible"
    :title="title || '设置查询条件'"
    class="min-height-500"
    width="900px"
    @confirm="handleConfirm"
  >
    <el-tabs v-if="inited" v-model="activeName">
      <el-tab-pane v-if="!isFilter" label="查询信息" name="first">
        <el-form :inline="true" :model="dialogConfig" label-width="100px" class="search-info-form">
          <el-row>
            <el-col v-if="tableId">
              <el-form-item label="表名称">
                <el-select v-model="dialogConfig.TableName" filterable @focus="loadSubTableName" @change="tableNameChange">
                  <el-option v-for="(item, index) in TableNames" :key="index" :label="item.table_name" :value="item.table_code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-else>
              <el-form-item label="表类型">
                <el-select v-model="dialogConfig.TableType" filterable @focus="loadTableType" @change="tableTypeChange">
                  <el-option v-for="(item, index) in TableTypes" :key="index" :label="item.type_name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="表名称">
                <el-select v-model="dialogConfig.TableName" filterable @focus="loadTableName" @change="tableNameChange">
                  <el-option v-for="(item, index) in TableNames" :key="index" :label="item.table_name" :value="item.table_code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="查询类型">
                <el-select v-model="dialogConfig.QueryMode" filterable>
                  <el-option v-for="(item, index) in pageSizeTypes" :key="index" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="分页大小">
                <el-input v-model="dialogConfig.PageSize" />
              </el-form-item> -->
            </el-col>
            <el-col>
              <tree-transfer
                ref="treeTransfer1"
                :func-code="funcCode"
                :json="filterJson"
                :datas="TableFields"
              />
            </el-col>
          </el-row>
          <el-row />
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="!isFilter" label="字段排序" name="second">
        <tree-transfer
          ref="treeTransfer2"
          :func-code="funcCode"
          :json="filterJson"
          :datas="TableFields"
          type="2"
        />
      </el-tab-pane>
      <el-tab-pane label="条件设置" name="third">
        <el-alert
          title="支持拖拽调整顺序"
          :closable="false"
          type="info"
        />
        <rule-config
          style="height:400px"
          :atoms="ruleFields"
          :rule="ruleFilter"
          :func-code="funcCode"
        />
      </el-tab-pane>
    </el-tabs>
  </common-dialog>
</template>
<script>
import {
  getDataSource,
  invokeMethod
} from '@admin/api/common'
function array2String(obj) {
  if (obj && obj.ChildFilters && obj.ChildFilters.length) {
    obj.ChildFilters.forEach(filter => {
      array2String(filter)
    })
  } else {
    if (obj.FilterName && Array.isArray(obj.FilterName)) {
      obj['FilterName'] = obj.FilterName.join('.')
    }
  }
}
function string2Array(obj) {
  if (obj && obj.ChildFilters && obj.ChildFilters.length) {
    obj.ChildFilters.forEach(filter => {
      string2Array(filter)
    })
  } else {
    if (obj.FilterName && typeof obj.FilterName === 'string') {
      obj['FilterName'] = obj.FilterName ? obj.FilterName.split('.') : []
    }
  }
}
const PAGESIZE_TYPES = [{
  code: '1',
  name: '分页查询'
}, {
  code: '2',
  name: '全部查询'
}]
export default {
  name: 'FilterDialog',
  props: {
    filterJson: {
      type: Object
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    // 树id
    treeId: {
      type: String,
      default: ''
    },
    isFilter: {
      type: Boolean,
      default: false
    },
    tableName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      filter: {}, // 筛选条件
      queryRows: {
        'fields': []
      },
      visible: false,
      dialogConfig: {},
      TableTypes: [],
      TableNames: [],
      TableFields: [],
      pageSizeTypes: PAGESIZE_TYPES,
      funcCode: '020101',
      activeName: 'first',
      value: [],
      inited: false,
      ruleFilter: {
        'FilterDisplay': '过滤条件设置',
        'And': true,
        'Not': false,
        'FilterName': null,
        'FilterValue': null,
        'FilterValueNAME': null,
        'OperateMode': 3,
        'ChildFilters': []
      },
      ruleFields: {}
    }
  },
  computed: {
    // 有treeId是从表单设计中添加子表，会做特殊处理
    tableId: function() {
      return this.treeId
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      handler: function(newvalue) {
        if (newvalue) {
          // 初始化页面
          this.inited = true
          this.getConfig()
          this.activeName = 'first'
          if (this.isFilter) {
            this.activeName = 'third'
            this.dialogConfig.TableName = this.tableName
            this.getTableFields()
          }
        } else {
          this.ruleFilter = this.$options.data().ruleFilter
        }
        this.visible = newvalue
      }
    },
    visible: function(newvalue) {
      this.$emit('update:dialogVisible', newvalue)
    }
  },
  methods: {
    getConfig() {
      if (this.filterJson.serverId) {
        this.dialogConfig = {}
        return
      }
      this.dialogConfig = this.filterJson ? JSON.parse(JSON.stringify(this.filterJson)) : {}
      this.dialogConfig = Object.assign({ PageSize: 10 }, this.dialogConfig)
      // 加载select
      if (this.dialogConfig.TableType) {
        this.TableTypes = [{
          id: this.dialogConfig.TableType,
          type_name: this.dialogConfig.TableTypeNAME
        }]
      }
      if (this.dialogConfig.TableName) {
        this.TableNames = [{
          table_code: this.dialogConfig.TableName,
          table_name: this.dialogConfig.TableNameNAME
        }]
        this.getTableFields()
      }
      if (this.dialogConfig.TableFilter) {
        const tableFilter = JSON.parse(JSON.stringify(this.dialogConfig.TableFilter))
        // string2Array(tableFilter)
        this.ruleFilter = tableFilter
      }
      this.visible = true
    },
    // 加载表类型
    loadTableType() {
      const param = {
        methodId: '2022052900030360493',
        data: {}
      }
      this.TableTypes = []
      getDataSource(param).then(res => {
        this.TableTypes = res.data
      })
    },
    // 表类型修改
    tableTypeChange() {
      this.dialogConfig.TableName = ''
      this.TableNames = []
      const cTableType = this.TableTypes.find(i => i.id === this.dialogConfig.TableType)
      if (cTableType) {
        this.dialogConfig.TableTypeNAME = cTableType['type_name']
      } else {
        this.dialogConfig.TableTypeNAME = ''
      }
    },
    // 加载子表
    loadSubTableName() {
      const param = {
        methodId: '686685662715318272',
        data: {
          p1: this.tableId
        }
      }
      getDataSource(param).then((res) => {
        this.TableNames = res.data
      })
    },
    // 加载表名
    loadTableName() {
      const tableType = this.dialogConfig.TableType
      if (!tableType) {
        this.$$message('请选择表类型')
        return
      }
      const param = {
        methodId: '2022052900033087332',
        data: { p1: tableType }
      }
      this.TableNames = []
      getDataSource(param).then(res => {
        this.TableNames = res.data
      })
    },
    // 表修改
    tableNameChange() {
      this.$bus.$emit('table-change')
      const cTable = this.TableNames.find(i => i.table_code === this.dialogConfig.TableName)
      if (cTable) {
        this.dialogConfig.TableNameNAME = cTable['table_name']
        this.dialogConfig.TableId = cTable['id']
      } else {
        this.dialogConfig.TableNameNAME = ''
        this.dialogConfig.TableId = ''
      }
      this.getTableFields()
    },
    // 获取列字段
    getTableFields() {
      const param = {
        methodId: '2022052900039377443',
        data: { tableCode: this.dialogConfig.TableName }
      }
      this.TableFields = []
      invokeMethod(param).then(res => {
        this.TableFields = res.data
        this.ruleFields = FDUI.fieldsToObject(res.data, 'code')
      })
    },
    handleConfirm() {
      const {
        codes,
        names
      } = this.$refs.treeTransfer1 ? this.$refs.treeTransfer1.getChecked() : {}
      const {
        codes: sortCodes,
        names: sortNames
      } = this.$refs.treeTransfer2 ? this.$refs.treeTransfer2.getChecked() : {}
      this.dialogConfig.TableFilter = this.ruleFilter
      this.dialogConfig.FixField = codes || ''
      this.dialogConfig.FixFieldNAME = names || ''
      this.dialogConfig.SortField = sortCodes || ''
      this.dialogConfig.SortNAME = sortNames || ''
      // 处理规则的filterName
      array2String(this.dialogConfig.TableFilter)
      this.$emit('confirm', JSON.stringify(this.dialogConfig))
      this.visible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-container{
  display: flex;
  justify-content: space-between;
  .filter-left{
    width: 100%;
  }
  .filter-right{
    margin-left: 12px;
    width: 100px
  }
  .search-info-form{

  }
}
</style>

